<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: gavin
 * Date: 15-3-25
 * Time: 下午2:12
 */
class Article extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->library('pagination');
        $this->load->model('ghc_user_model');
        $this->load->model('ghc_sort_model');
        $this->load->model('ghc_blog_model');
    }

    public function index()
    {
        if(!$this->is_Session())
        {
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }else{
            header("location:".SITE_URL.'index.php/article/lists');
            exit;
        }

    }

    /**
     *进入编辑页面
     */
    public function editor()
    {
        if(!$this->is_Session())
        {
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }
        $data['username'] = $this->session->userdata('username');
        if($this->input->get('qid'))
        {//update mod
            $data['blog'] = $this->ghc_blog_model->getBlogById($this->input->get('qid'));

            if(empty($data['blog']))
            {//fake data
                unset($data);
            }

        }

        $sorts = $this->ghc_sort_model->getSorts();
        for($i=0;$i<count($sorts);$i++)
        {
            $data['sort'][$i]['sid'] = $sorts[$i]->sid;
            $data['sort'][$i]['sortname'] = $sorts[$i]->sortname;
        }
        $this->load->view('admin/writearticle',$data);
    }

    /**
     * @param string $offset
     * 后台获取文章列表
     */
    public function lists($offset='')
    {
        if(!$this->is_Session())
        {
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }
        $data['username'] = $this->session->userdata('username');
        $users = $this->ghc_user_model->getUsers();
        $data['author'] = null;
        $data['sort'] = null;
        for($i=0;$i<count($users);$i++)
        {
            $data['author'][$users[$i]->uid] = $users[$i]->username;
        }
        $sorts = $this->ghc_sort_model->getSorts();
        for($i=0;$i<count($sorts);$i++)
        {
            $data['sort'][$sorts[$i]->sid] = $sorts[$i]->sortname;
        }

        #配置分页信息
        $config['base_url'] = SITE_URL.'index.php/article/lists/';
        $config['total_rows'] = $this->ghc_blog_model->getAllNums();//总数
        $config['per_page'] = 6;
        $config['uri_segment'] = 3;

        #自定义分页链接
        $config['first_link'] = '首页';
        $config['last_link'] = '尾页';
        $config['prev_link'] = '上一页';
        $config['next_link'] = '下一页';

        #初始化分页类
        $this->pagination->initialize($config);

        #生成分页信息
        $data['pageinfo'] = $this->pagination->create_links();

        $limit = $config['per_page'];

        $data['blogs'] = $this->ghc_blog_model->listBlog($limit,$offset);


        $this->load->view('admin/articlelists',$data);

    }

    /**
     * @param string $sortname
     * 设置分类
     */
    public function setsort($sortname='')
    {
        $this->ghc_sort_model->insert('通知公告');
        //工作动态下的4个
        $this->ghc_sort_model->insert('规划工作');
        $this->ghc_sort_model->insert('校友工作');
        $this->ghc_sort_model->insert('合作发展');
        $this->ghc_sort_model->insert('内部建设');
        //资料荟萃下的
        $this->ghc_sort_model->insert('领导讲话');
        $this->ghc_sort_model->insert('政策法规');
        $this->ghc_sort_model->insert('指导意见');
        $this->ghc_sort_model->insert('其他资料');
        //发展规划下的
        $this->ghc_sort_model->insert('国家政策');
        $this->ghc_sort_model->insert('省市规划');
        $this->ghc_sort_model->insert('学校规划');
        $this->ghc_sort_model->insert('规划参考');
        //战略研究下的
        $this->ghc_sort_model->insert('专题研究');
        $this->ghc_sort_model->insert('参考资讯');
        $query = $this->ghc_sort_model->getSorts();
        header("charset='utf-8'");
        //echo "OK";
        var_dump($query);
    }

    /**
     *ajax添加文章
     */
    public function addarticle()
    {
        if(!$this->is_Session())
        {
            echo "addarticle error";
            exit;
        }
        $this->form_validation->set_rules('title','title','trim|required|xss_clean');
        $this->form_validation->set_rules('date','date','trim|required|xss_clean');
        //$this->form_validation->set_rules('content','content','trim|required|xss_clean');
        $this->form_validation->set_rules('sortid','sortid','trim|integer|required|xss_clean');

        if($this->form_validation->run()  == TRUE)
        {
            $title = $this->input->post('title');
            $date =  intval(strtotime($this->input->post('date')),10)+(time()-strtotime(date('Y-m-d',time())));
            $content = $this->input->post('content');
            $author = intval($this->session->userdata('userid'),10);
            $sortid = $this->input->post('sortid');
            //正则获取第一张照片
            preg_match('/img src=".*?"/',$content,$res);
            $str = null;
            if(count($res) != 0)
            {
                $str = $res[0];
                $str = ltrim($str,'img src="');
                $str = rtrim($str,'"');
            }
            $this->ghc_blog_model->insert($title,$date,$content,$author,$sortid,$str);
            //var_dump($res);
            //echo $content;
            echo "ok";
        }
        else{

            echo "error";
        }
        return;
    }

    /**
     *ajax update 文章
     */
    public function updatearticle()
    {
        if(!$this->is_Session())
        {
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }
        $this->form_validation->set_rules('title','title','trim|required|xss_clean');
        $this->form_validation->set_rules('date','date','trim|required|xss_clean');
        //$this->form_validation->set_rules('content','content','trim|required|xss_clean');
        $this->form_validation->set_rules('sortid','sortid','trim|integer|required|xss_clean');
        $this->form_validation->set_rules('qid','qid','trim|integer|required|xss_clean');

        if($this->form_validation->run()  == TRUE)
        {
            $title = $this->input->post('title');
            $date =  intval(strtotime($this->input->post('date')),10)+(time()-strtotime(date('Y-m-d',time())));
            $content = $this->input->post('content');
            $author = intval($this->session->userdata('userid'),10);
            $sortid = $this->input->post('sortid');
            $qid = $this->input->post('qid');

            //正则获取第一张照片
            preg_match('/img src=".*?"/',$content,$res);
            $str = null;
            if(count($res) != 0)
            {
                $str = $res[0];
                $str = ltrim($str,'img src="');
                $str = rtrim($str,'"');
            }
            $this->ghc_blog_model->update($qid,$title,$date,$content,$author,$sortid,$str);
            //echo $content;
            echo "ok";
        }
        else{

            echo "error";
        }
        return;
    }

    /**
     *ajax 删除文章
     */
    public function deletearticle()
    {
        if(!$this->is_Session())
        {
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }
        $qid = $this->input->post('qid');
        echo $this->ghc_blog_model->hideBlogById($qid);
        echo 'OK';
        return;
    }

    /**
     * @return bool
     * 判断是否存在username 和 role(角色)
     */
    private function is_Session()
    {
        $userid = $this->session->userdata('userid');
        $value = $this->session->userdata('username');
        $role = $this->session->userdata('role');
        if($value && $role && $userid)
        {
            return TRUE;
        }
        else
        {
            $log = sprintf("no login visit,  IP:%s, UserAgent:%s.",$this->input->ip_address(),$this->input->user_agent());
            log_message('error', $log);
            return FALSE;
        }
    }

    public function test($qid=1)
    {
        $blog = $this->ghc_blog_model->getBlogById($qid);
        $this->ghc_blog_model->addView($qid);
        header("Content-type: text/html; charset=utf-8");
        var_dump($blog);
    }
}